package com.dt.zbcy.provider.core.handle;

import com.baomidou.mybatisplus.entity.TableFieldInfo;
import com.baomidou.mybatisplus.entity.TableInfo;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import org.apache.commons.lang3.StringUtils;

import java.util.Iterator;
import java.util.List;

/**
 * @author: leiliang.<br>
 * 创建时间: 2018-12-13 下午10:30.<br>
 * 功能描述: todo .<br>
 */
public class DtLogicSqlInjector extends LogicSqlInjector {

    @Override
    protected String sqlWhereEntityWrapper(TableInfo table) {
        if(!table.isLogicDelete()) {
            return super.sqlWhereEntityWrapper(table);
        } else {
            StringBuilder where = new StringBuilder(128);
            where.append("\n<where>");
            where.append("\n<choose><when test=\"ew!=null\">");
            where.append("\n<if test=\"ew.entity!=null\">");
            if(StringUtils.isNotEmpty(table.getKeyProperty())) {
                where.append("\n<if test=\"ew.entity.").append(table.getKeyProperty()).append("!=null\">");
                where.append(" AND ").append(table.getKeyColumn()).append("=#{ew.entity.");
                where.append(table.getKeyProperty()).append("}");
                where.append("</if>");
            }

            List fieldList = table.getFieldList();
            Iterator i$ = fieldList.iterator();

            while(i$.hasNext()) {
                TableFieldInfo fieldInfo = (TableFieldInfo)i$.next();
                where.append(this.convertIfTag(fieldInfo, "ew.entity.", false));
                where.append(" AND ").append(this.sqlCondition(fieldInfo.getCondition(), fieldInfo.getColumn(), "ew.entity." + fieldInfo.getEl()));
                where.append(this.convertIfTag(fieldInfo, true));
            }

            where.append("\n</if>");
            where.append("\n<if test=\"ew.sqlSegment!=null\">${ew.sqlSegment}\n</if>");
            where.append("\n</when><otherwise>");
            where.append("\n</otherwise></choose>");
            where.append("\n").append(this.getLogicDeleteSql(table));
            where.append("\n</where>");
            return where.toString();
        }
    }
}
